import requests
import json
import os
from threading import Thread
from src.utils.config import config
import socket
# from src.utils.hashlib_utils import hashForString
from src.utils.config import logger

def get_host_ip():
    """
    查询本机ip地址
    :return: ip
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
        return ip

class FeishuMessager:
    def __init__(self):
        self.message_url = config.get_config('feishu', 'feishu_url')
        self.robot_v1 = config.get_config('feishu', 'robot_v1')
        self.headers = {
            "Content-Type": "application/json",
            "alertToken": "17d0599c49e82b2d"
        }
        self.form_data = {
            "chatId": config.get_config('feishu', 'robot'),
            'title': '[价格]模型监控',
            "sendTextInfoType":"rich_text",
            "text": [
            ]
        }

    def async(f):
        def wrapper(*args, **kwargs):
            thr = Thread(target=f, args=args, kwargs=kwargs)
            thr.start()

        return wrapper

    @async
    def send_message(self, message,title='[{}价格]模型监控！\n详情：',chatid=1):
        form_data = self.form_data.copy()
        server = os.environ.get('API_SERVER_INFO')
        # msg = "## [价格]模型监控！\n详情："+message
        env = 'test' if os.environ.get('environment') is None else os.environ.get('environment')
        # title = "## [{}价格]模型监控！\n详情："
        title=title.format(env)
        form_data['title']=title
        msg = message
        if server is not None:
            msg = msg + '  \nFrom Price Model server@{}'.format(server)
        else:
            try:
                server = get_host_ip()
                msg = msg + '  \nFrom Price Model server@{}'.format(server)
            except Exception as e:
                logger.critical('获取ip报错：@{}'.format(e))
        # if os.environ.get('environment') == 'deploy':
        #     # product环境
        #     form_data['message'] = msg
        # else:
        #     # 测试环境在message前后加入"测试"字样
        #     msg = msg
        #     form_data['message'] = msg
        # hashMd5= hashForString("md5",msg)
        # state = redis_conn.get(hashMd5)
        # if state is None :
        #     redis_conn.set(hashMd5, 1, ex=60*1)
        # else:
        #     return
        data=[{"text": msg}]
        form_data['text'] = data
        if chatid==2:
            form_data['chatId']=self.robot_v1
        requests.post(self.message_url, headers=self.headers,
                      data=json.dumps(form_data), timeout=5)


feishu_messager = FeishuMessager()
